#include <SFML/Graphics.hpp>
#include <time.h>
#include <iostream>
using namespace std;
using namespace sf;

int wt = 720; // 宽
int ht = 560; // 高

// 碰撞
bool isCollide(Sprite &sp1, Sprite &sp2)
{
	// getGlobalBounds 返回 精灵所在的矩形
	// intersects 检查两个矩形之间的交点
	return sp1.getGlobalBounds().intersects(sp2.getGlobalBounds());
}

int main()
{
	srand(time(0));
	sf::RenderWindow window(sf::VideoMode(wt, ht), "Arkanoid! --YzHCat");
	window.setFramerateLimit(60);

	Texture t1, t2, t3, t4;
	t1.loadFromFile("../images/block01a.png");
	t2.loadFromFile("../images/background.png");
	t3.loadFromFile("../images/ball.png");
	t4.loadFromFile("../images/platform.png");

	Sprite s_background(t2), s_ball(t3), s_plat(t4);
	Vector2f cb{6, 6}; // 设置球心为原点
	s_ball.setOrigin(cb.x, cb.y);
	// 初始位置
	s_plat.setPosition(wt / 2, ht - 10);  // 平台
	s_ball.setPosition(wt / 2, ht - 150); // 球

	Sprite s_block[1000]; // 砖块
	int n = 0;
	for (int i = 0; i < 15; i++)
		for (int j = 0; j < 10; j++)
		{
			s_block[n].setTexture(t1);
			s_block[n].setPosition(i * 43, j * 20); // 方块42*20px
			s_block[n].move(38, 20);				// 边界留空
			n++;
		}

	float dy = 5, dx = 6; // 偏移

	int run = 1;
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
			if (event.type == Event::KeyPressed) // 按下
			{
				if (event.key.code == Keyboard::Escape)
					window.close();
				if (event.key.code == Keyboard::Space)
					run = 1 - run;
			}
		}
		if (run)
		{
			// move偏移函数 使对象在之前位置上加上偏移量X,Y (pos.x + offsetX, pos.y + offsetY)
			s_ball.move(dx, 0); // 碰撞有两种方向，要分别控制
			for (int i = 0; i < n; i++)
				if (isCollide(s_ball, s_block[i]))
				{
					s_block[i].setPosition(-100, 0);
					dx = -dx;
				}

			s_ball.move(0, dy); // 碰撞有两种方向，要分别控制
			for (int i = 0; i < n; i++)
				if (isCollide(s_ball, s_block[i]))
				{
					s_block[i].setPosition(-100, 0);
					dy = -dy;
				}

			Vector2f b = s_ball.getPosition();
			// 边界检查
			if (b.x - cb.x < 0 || b.x + cb.x > wt)
				dx = -dx;
			if (b.y - cb.y < 0)
				dy = -dy;
			if (b.y + cb.y > ht)
			{
				run = 0;
				dy = -dy;
			}
			// 平台移动
			b = s_plat.getPosition();
			if (b.x > 0) // 平台边界
				if (Keyboard::isKeyPressed(Keyboard::Left))
					s_plat.move(-8, 0);
			if (b.x + 90 < wt)
				if (Keyboard::isKeyPressed(Keyboard::Right))
					s_plat.move(8, 0);

			if (isCollide(s_plat, s_ball))
				dy = -((rand() % (5 - 2)) + 3);
			window.clear();
			window.draw(s_background);
			window.draw(s_ball);
			window.draw(s_plat);
			window.draw(s_ball);

			for (int i = 0; i < n; i++)
				window.draw(s_block[i]);

			window.display();
		}
	}

	return 0;
}
